package com.atguigu.serviceedu.controller;


import com.atguigu.common.enums.ResponseEnum;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.utils.R;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.serviceedu.feign.ServiceVodFeign;
import com.atguigu.serviceedu.service.EduVideoService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 * @author yzh
 * @since 2022-01-15
 */
@RestController
@RequestMapping("/video")
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;
    @Autowired
    private ServiceVodFeign serviceVodFeign;

    @ApiOperation("根据ID获取课程视频")
    @GetMapping("{id}")
    public R getVideoById(
            @ApiParam(name = "id", value = "课程视频ID", required = true)
            @PathVariable String id) {
        return R.ok().data("video", videoService.getById(id));
    }

    @ApiOperation("保存课程视频")
    @PostMapping
    public R addVideo(
            @ApiParam(name = "video", value = "课程视频", required = true)
            @RequestBody EduVideo video) {
        return videoService.save(video) ? R.ok(ResponseEnum.ADD_SUCCESS) : R.error(ResponseEnum.ADD_FAIL);
    }

    @ApiOperation("修改课程视频")
    @PutMapping
    public R updateVideo(
            @ApiParam(name = "video", value = "课程视频", required = true)
            @RequestBody EduVideo video) {
        return videoService.updateById(video) ? R.ok(ResponseEnum.UPDATE_SUCCESS) : R.error(ResponseEnum.UPDATE_FAIL);
    }

    @ApiOperation("删除课程视频")
    @DeleteMapping("{id}")
    public R deleteVideo(
            @ApiParam(name = "id", value = "课程视频ID", required = true)
            @PathVariable String id) {
        // 根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //判断小节里面是否有视频id
        if (!StringUtils.isEmpty(videoSourceId)) {
            //根据视频id，远程调用实现视频删除
            R result = serviceVodFeign.removeAlyVideo(videoSourceId);
            Assert.notEquals(result.getCode(), 20001, ResponseEnum.DELETE_FAIL);
        }

        return videoService.removeById(id) ? R.ok(ResponseEnum.DELETE_SUCCESS) : R.error(ResponseEnum.DELETE_FAIL);
    }

}

